const Koa = require('koa')
const request = require('request')
const Router = require('koa-router')
const cors = require('koa2-cors')

const app = new Koa()
app.use(cors())
const router = new Router()

function ajax (config) {
  return new Promise((resolve, reject) => {
    request(config, function (error, response, body) {
      const res = JSON.parse(body)
      if (error || res.ec !== 0) {
        reject(error || res)
      }
      resolve(res)
    })
  })
}

// 获取群列表
router.get('/get_group_list', async (ctx) => {
  try {
    const res = await ajax({
      url: `http://qun.qq.com/cgi-bin/qun_mgr/get_group_list?bkn=${ctx.query.bkn}`,
      method: 'Post',
      headers: {
        cookie: ctx.query.cookie
      }
    })
    ctx.headers['content-type'] = 'application/json'
    let arr = []
    if (res.join) {
      res.join.forEach(item => {
        arr.push({
          gid: item.gc,
          name: item.gn
        })
      })
    }
    if (res.manage) {
      res.manage.forEach(item => {
        arr.push({
          gid: item.gc,
          name: item.gn
        })
      })
    }
    if (res.create) {
      res.create.forEach(item => {
        arr.push({
          gid: item.gc,
          name: item.gn
        })
      })
    }
    ctx.body = arr
  } catch (error) {
    ctx.status = 500
    ctx.body = error
  }
})

router.get('/search_group_members', async (ctx) => {
  try {
    const res = await ajax({
      url: `http://qun.qq.com/cgi-bin/qun_mgr/search_group_members?bkn=${ctx.query.bkn}&gc=${ctx.query.gc}&st=${ctx.query.st}&end=${ctx.query.end}&sort=0`,
      method: 'Post',
      headers: {
        cookie: ctx.query.cookie
      }
    })
    ctx.headers['content-type'] = 'application/json'
    ctx.body = res
  } catch (error) {
    ctx.status = 500
    ctx.body = error
  }
})


app.use(router.routes());
app.use(router.allowedMethods({ 
  // throw: true, // 抛出错误，代替设置响应头状态
  // notImplemented: () => '不支持当前请求所需要的功能',
  // methodNotAllowed: () => '不支持的请求方式'
}));

app.listen(4000, () => {
  console.log('server is running')
})

